package com.bf.xpdd.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bf.xpdd.config.ConfigParameter;
import com.bf.xpdd.domain.SiteBuyer;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.exception.BaseException;

/**
 * Web Interceptor
 * 
 * @author Fantastic
 * @version 1.0.0 2011-05-31
 * @since 1.0.0
 */
public class WebInterceptor extends HandlerInterceptorAdapter
{
	/** log4j */
	private static final Logger logger = Logger.getLogger(WebInterceptor.class);
	
	/** default servlet prefix */
	private static final String DEFAULT_SERVLET_PREFIX = "/xpdd";
	
	/** back controllers */
	private static final String[] BACK_CONTROLLERS = new String[]{"/activity", "/setting", "/analysis", "/theme"};
	
	/** front controllers */
	private static final String[] FRONT_CONTROLLERS = new String[]{"/front"};
	
	/** will be injected from context configuration file */
	// private AclService service;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception
	{
		String currentUri = request.getRequestURI();
		boolean isAccessible = true;
		// only intercept for annotated business controllers
		Controller c = AnnotationUtils.findAnnotation(handler.getClass(),
				Controller.class);
		if (c != null)
		{
			String[] grantedResource = this.getGrantedResource(request);
			if (grantedResource == null || grantedResource.length == 0)
			{
				throw new BaseException("No resource granted");
			}
			
//			currentUri = currentUri.replaceAll("/xpdd", "");
			if(this.hasController(currentUri, BACK_CONTROLLERS))
			{
				// validate seller
				Object seller = request.getSession(true).getAttribute("seller");
				if (null == seller)
				{
					response.sendRedirect(ConfigParameter.BACK_CALL_BACK_URL);
					return false;
				}
			}
			else if(this.hasController(currentUri, FRONT_CONTROLLERS))
			{
				// validate buyer
//				Buyer buyer = (Buyer) request.getSession(true).getAttribute("buyer");
//				if (null == buyer)
//				{
//					response.sendRedirect(ConfigParameter.FRONT_CALL_BACK_URL);
//				}
			}

			// isAccessible = service.isAccessible(grantedResource, currentUri);
			if (logger.isDebugEnabled())
			{
				logger.debug("interceptor excueted. Accessible for Uri["
						+ currentUri + "] = " + isAccessible);
			}
			// if isAccessible==true, throw custom AccessDeniedException
			if (!isAccessible)
				throw new BaseException("access faild");
		}
		
		return isAccessible;
	}
	
	/**
	 * transfer the original Uri to resource Uri e.g.: original Uri:
	 * /servlet/hotels/ajax target Uri : /hotels/ajax
	 * 
	 * @param originalUri
	 * @return
	 */
	protected String getUri(String originalUri)
	{
		return originalUri.substring(DEFAULT_SERVLET_PREFIX.length());
	}

	/**
	 * Get the granted resource from session
	 * 
	 * @param request
	 * @return
	 */
	protected String[] getGrantedResource(HttpServletRequest request)
	{
		// get the resources from current session
		// String[] uriResourcePattern = (String[])
		// request.getSession().getAttribute("uriResourcePattern");
		// TODO: mock data here
		String[] uriResourcePattern = new String[] { "/**" };

		return uriResourcePattern;
	}
	
	/**
	 * 查看是否包含该uri
	 * @param uri
	 * @param controllers
	 * @return 是否
	 */
	private boolean hasController(String uri, String[] controllers)
	{
		for(String controller : controllers)
		{
			if(uri.startsWith(controller))
			{
				return true;
			}
		}
		return false;
	}
}
